#ifndef _SERVER_H
#define _SERVER_H

#include "yamlHandler.h"
#include "dataBase_test.h"
#include <thread>
#include <mutex>
#include <unistd.h>
#include <memory.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 2333
#define MAXLINE 4096
//协议帧
#define BEATFRAME "\n\r"
#define COMMAND 0
#define LABLE 1
#define CONTENT 2

class TicToc
{
    long int count;
    std::thread tic_thread;
    std::mutex lock;
    void threadFunction(){
        while(true)
        {
            lock.lock();
            count++;
            lock.unlock();
            sleep(1);
        }
    }
public:
    TicToc(){
        tic_thread = std::thread([this](){this->threadFunction();});
        count = 0;
    }
    void tic(){
        lock.lock();
        count = 0;
        lock.unlock();
    }
    int toc()
    {
        return count;
    }
};

class LinkControl
{
    struct sockaddr_in servaddr;
    char buff[MAXLINE];
    int listenfd, connfd;
    std::string msg;
    int userAuth(std::string msg, StuDataStruct& stu_data);
public:
    LinkControl(){
        if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        {
            std::cerr << "create socket error" << std::endl;
        }
        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        servaddr.sin_port = htons(PORT);
        if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
        {
            std::cerr << "bind socket error" << strerror(errno) << std::endl;
        }
        if(listen(listenfd, 10) == -1)
        {
            std::cerr << "listen socket error" << strerror(errno) << std::endl;
        }
        else
        {
            std::cout << "========== waiting for connection ==========" << std::endl;
        }
    }	
    int run();
    std::string recvData();
    bool sendData(std::string data);
    void toDataBase(StuDataStruct stu_data);
    void toDataBaseSuper();
};

extern TicToc g_tictoc;

#endif
